<?php

namespace addons\booking\controller;

use addons\booking\model\RoomState;
use addons\booking\model\Store as StoreModel;
use addons\booking\model\Worker as WorkerModel;
use addons\booking\model\HouseMode;
use addons\booking\model\HouseFloor;
use addons\booking\model\House as HouseModel;
use addons\booking\model\HouseGuide;
use addons\booking\model\StoreOrder as StoreOrderModel;
use addons\booking\model\StoreOrderSon;

use think\Db;
use think\Session;


class StoreOrder extends Base
{
    protected $noNeedLogin = [];
    protected $modelValidate = true; //是否开启Validate验证，默认是false关闭状态
    protected $modelSceneValidate = true; //是否开启模型场景验证，默认是false关闭状态

    //发布订单
    public function create()
    {
        $store_id = $this->request->param('store_id/d',0);
        $store_user_id = $this->request->param('store_user_id/d',0);
        $room_num = $this->request->param('room_num/d',0);
        $arrival_time = $this->request->param('arrival_time',0);
        $worker_num = $this->request->param('worker_num/d',0);
        $workers = $this->request->param('workers','');//优先接单的保洁
        $mark = $this->request->param('mark','');//备注
        $expected_cleaning_price = $this->request->param('costs_clean_price',0);
        $additional_price  = $this->request->param('add_price',0);
        $urgent_price  = $this->request->param('urgent_price',0);
        $total_expected_price = $this->request->param('costs_total_price',0);

        if(!$store_id)   $this->error('参数错误');
        if(!$room_num)   $this->error('房间数必须填');
        if(!$worker_num)   $this->error('保洁数必须填');
        if(!$arrival_time)   $this->error('预约时间必须填');

        //验证当前发单员是否为酒店当前值班人员
        //验证当前是否有未结清的订单
        //验证当前是否有未支付的订单
        $orderInfo = StoreOrderModel::where('store_id',$store_id)->where('status','in',[0,1])->find();
        if($orderInfo){
            if($orderInfo['margin_paid']  ==  0) {
                $this->error('还有未支付的订单,无法发单');
            } else if(in_array($orderInfo['status'],[0,1])) {
                $this->error('还有未结清的订单,无法发单');
            }
        }

        $arrival_date = date('Ymd',$arrival_time);
        $pay_margin_price = 100;//保证金
        $data = [
            'order_sn' => StoreOrderModel::uni_order_sn(),
            'store_id' => $store_id,
            'room_num' => $room_num,
            'worker_num' => $worker_num,
            'mark'  => $mark,
            'costs_clean_price' => $expected_cleaning_price,
            'add_price' => $additional_price,
            'urgent_price' => $urgent_price,
            'costs_total_price' =>$total_expected_price,
            'store_user_id' =>$store_user_id,
            'status' => 0 ,
            'arrival_time' => $arrival_time,
            'arrival_date' => $arrival_date,
            'create_time' => time(),
            'pay_margin_price' => $pay_margin_price,
            'time_key' => currentTime($arrival_time)
        ];

        DB::startTrans();
        try{
            //添加订单
            $order_id = Db::name('store_order')->insertGetId($data);
            //添加提前优先的保洁
            $time = time();
            $workers_data = [];
            //组装优先接单保洁
            if($workers){
                $workers_arr = explode(',',$workers);
                foreach ($workers_arr as $k=>$v){
                    $map = [];
                    $map['store_id'] = $store_id;
                    $map['order_id'] = $order_id;
                    $map['worker_id'] = $v;
                    $map['create_time'] = $time;
                    $workers_data[] = $map;
                }
            }
            if($workers_data){
                Db::name('order_first')->insertAll($workers_data);
            }

            $res = 1;
            $msg = '添加成功';
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $res = 2;
            $msg = '添加失败';
        }
        if($res == 1){
            $this->success($msg,['order_id'=>$order_id]);
        } else {
            $this->error($msg);
        }
    }

    //计算订单金额
    public function compute()
    {
        $store_id = $this->request->param('store_id/d',0);//酒店id
        $room_num = $this->request->param('room_num/d',0);//发布的房间数
        if(!$store_id || !$room_num)   $this->error('参数错误');
        $fine_room_num  = 15;//罚款房间数
        $fine_money  = 20;//罚款金额

        $costs_clean_price = HouseModel::where('id',$store_id)->avg('price');
        $costs_clean_price = number_format($costs_clean_price,2);//预计单价

        $add_price = 0;//附加费用

        $store_money = StoreModel::where('id',$store_id)->value('money');
        $pay_margin_price = 100;//保证金

        $data = compact('fine_room_num','fine_money','costs_clean_price','add_price','store_money','pay_margin_price');
        $this->success('',$data);

    }

    //支付保证金
    public function pay_margin()
    {
        $order_id = $this->request->param('order_id/d',0);//酒店id
        $pay_type = $this->request->param('pay_type','');//支付方式
        $order_info = StoreOrderModel::where('id',$order_id)->find();
        if(!$order_info) $this->error('订单不存在');
        if($order_info['margin_paid'] != 0) $this->error('当前状态无法支付');
        if(!$pay_type) $this->error('重新支付选择支付方式');

        $order['margin_pay_type'] = $pay_type; //重新支付选择支付方式
        $order['margin_pay_sn'] = StoreOrderModel::uni_order_sn();
        StoreOrderModel::where('id',$order_id)->update($order);

        $order = StoreOrderModel::where('id',$order_id)->find();
        switch ($order['margin_pay_type']) {
            case 'weixin':

            case 'alipay':

            case 'balance':
                $pay = StoreOrderModel::yueMarginPay($order->toArray(),$order['store_id']);
                if ($pay['status'] === true)
                    $this->success('余额支付成功',['order_id'=>$order_id]);
                else {
                    $this->error($pay['msg']);
                }
        }
    }

    //订单列表
    public function order_list()
    {
        $store_id = $this->request->param('store_id/d',0);
        $type = $this->request->param('type/d',0);
        $page = $this->request->param('page/d',1);
        $limit = $this->request->param('limit/d',10);
        if(!$store_id) $this->error('订单不存在');
        $list = StoreOrderModel::getList($store_id,$type,$page,$limit);
        $this->success('',$list);
    }

    //订单详情
    public function order_detail()
    {

    }

    //取消订单
    public function cancel_order()
    {
        $order_id = $this->request->param('order_id/d',0);
        $order = StoreOrderModel::where('id',$order_id)->find();
        if($order['status'] !=0 ) $this->error('该订单无法取消');

        $res  = StoreOrderModel::cancel_order($order_id);
        if($res['status'] == 1){
            $this->success($res['msg'],['order_id'=>$order_id]);
        } else {
            $this->error($res['msg']);
        }
    }

    //结束保洁的子订单
    public function end_order()
    {

    }


    //分派房间
    public function assign_room()
    {
        $order_id = $this->request->param('order_id/d',0);
        $worker_id =  $this->request->param('worker_id/d',0);
        $rooms = $this->request->param('rooms','');
        if(!$order_id || !$worker_id) $this->error('缺少参数');
        if(!$rooms) $this->error('请选择分配房间');

        $res  = StoreOrderModel::assign_room($order_id,$worker_id,$rooms);
        if($res['status'] == 1){
            $this->success($res['msg']);
        } else {
            $this->error($res['msg']);
        }
    }


    //房态统计
    public function order_count()
    {
        $date_type = $this->request->param('date_type/d',1);
        $store_id = $this->request->param('store_id/d',0);

        if(!$store_id) $this->error('参数错误');


        $data = [
            'room'=>['total' => 100,  //全部
                'empty_clean' => 10, //空净
                'empty_dirty' => 10, //空脏
                'no_empty_clean' =>10,  //住净
                'no_empty_dirty' =>10,  //住脏
            ],
            'order'=>[
                'order_dirty' =>10 ,  //脏房
                'order_assigned' =>10, //已分派
                'order_cleaning' => 10, //打扫中
                'order_accepted' => 10, //待验收
                'order_clean' => 10, //净房
            ],
            'received_order' => [//已接单
                'paln_room' => 30, //计划房间数
                'assigned_room' => 20,//已分派房间数
                'worker_num' => 5, //接单保洁
            ],
            'unaccepted_orders' => [//未接单
                'paln_room' => 30, //计划房间数
                'worker_num' => 10, //计划保洁数
            ]
        ];

        $this->success('',$data);
    }

    //接单保洁列表
    public function receiving_worker()
    {
        $order_id = $this->request->param('order_id/d',0);
        if(!$order_id) $this->error('参数错误');

        $list = StoreOrderSon::receiving_worker($order_id);
        $this->success('',$list);
    }

}
